import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { EntityManager, Repository } from 'typeorm';
import { DEFAULT_PAGE_SIZE } from '../config/contants';

import { TbUser } from '../entities/TbUser';

@Injectable()
export class UserModel {
  constructor(
    @InjectRepository(TbUser)
    private readonly tbUserRepository: Repository<TbUser>,
  ) {}

  // 查询用户列表
  async getUserList(
    address: string,
    age: number,
    limit: number,
    offset: number,
  ): Promise<[TbUser[], number]> {
    if (!offset || offset < 0) {
      offset = 0;
    }

    if (!limit || limit < 1) {
      limit = DEFAULT_PAGE_SIZE;
    }

    let where: any = { address };
    if (age > 0) {
      where.age = age;
    }

    return await this.tbUserRepository.findAndCount({
      where,
      skip: offset,
      take: limit,
      order: {
        id: 'DESC',
      },
    });
  }

  // 查询用户详情
  async getUserById(id: number): Promise<TbUser> {
    return await this.tbUserRepository.findOne({
      where: {
        id,
      },
    });
  }

  async getUserByAddress(address: string): Promise<TbUser> {
    return await this.tbUserRepository.findOne({
      where: {
        address,
      },
    });
  }

  async getUserByRealName(realName: string): Promise<TbUser> {
    return await this.tbUserRepository.findOne({
      where: {
        realName,
      },
    });
  }

  // 增加或保存用户
  async saveUser(data: any, manager: EntityManager = null): Promise<TbUser> {
    if (!data.id || data.id == 0) {
      data.createdAt = new Date();
    }
    data.updatedAt = new Date();

    try {
      if (manager) {
        return await manager.save(data); // 便于在事务中执行
      } else {
        return await this.tbUserRepository.save(data);
      }
    } catch (error) {
      console.error('saveUser error:', error);
      throw error;
    }

    // 执行原生sql
    // await this.tbUserRepository.query('UPDATE tb_user SET real_name="simon" where id=1');
  }

  // 删除用户
  async delUser(
    id: number,
    address: string,
    manager: EntityManager = null,
  ): Promise<void> {
    let where: any = {
      id,
    };
    if (address) {
      where.address = address;
    }

    try {
      if (manager) {
        await manager.delete(TbUser, where);
      } else {
        await this.tbUserRepository.delete(where);
      }
      // 执行原生sql
      // await this.tbUserRepository.query(`delete from tb_user where id=${id}`);
    } catch (error) {
      console.error('delUser error:', error);
      throw error;
    }
  }
}
